hex2bin={'0':'0000','1':'0001','2':'0010','3':'0011',
	'4':'0100','5':'0101','6':'0110','7':'0111',
	'8':'1000','9':'1001','a':'1010','b':'1011',
	'c':'1100','d':'1101','e':'1110','f':'1111'}
def bin(n):
	"""Convert a int number to binary string"""
	hexstr=hex(n)[2:]
	b=''
	for digit in hexstr:
		try:
			b+=hex2bin[digit]
		except KeyError,k:
			if k=='L':pass
		except:
			raise
	return b.lstrip('0')
	
def bin2int(binstr):
	"""	Convert a bits string into a integer list, one byte per step"""
	bits = len(binstr)
	intlist = []
	for i in range(0,bits,8):
		n = 0
		for j in range(0, 8):
			try:
				n += int(binstr[-(i+j+1)])*(2**j)
			except IndexError:
				break
		intlist.insert(0,n)
	return intlist
			
def bin2hex(binstr):
	'''convert bits string into hex str '''
	intlist = bin2int(binstr)
	return '0x'+"".join(hex(i)[2:] for i in intlist)
	
def utf8_16(binstr):
	"""UTF-8 characters have formation like: [0xxxxxxx](1byte),[110xxxxx][10xxxxxx](2bytes),
	[1110xxxx][10xxxxxx][10xxxxxx](3bytes).This function can eliminate prepending marks, 
	get the bits with meaning, and transform them into a hexadecimal string"""
	bits=len(binstr)
	if bits%8!=0:
		return False
	bytelist=[binstr[byteidx:byteidx+8] for byteidx in range(0,bits,8)]
	charlist=[]
	i=0
	while i<len(bytelist):
		step,char = 1,''
		if bytelist[i][0]=='0':#1byte
			char=bytelist[i]
		elif bytelist[i][0:3]=='110':#2bytes
			char=bytelist[i][3:8]+bytelist[i+1][2:8]
			step=2
		elif bytelist[i][0:4]=='1110':#3bytes
			char=bytelist[i][4:8]+bytelist[i+1][2:8]+bytelist[i+2][2:8]
			step=3
		elif bytelist[i][0:5]=='11110':#4bytes for supplement planes
			char=bytelist[i][5:8]+bytelist[i+1][2:8]+bytelist[i+2][2:8]+bytelist[i+3][2:8]
			step=4
		else:
			return False
		i+=step
		charlist.append(char)
	return bin2hex("".join(charlist))

	
